﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

static class tcode
{
    static harfbuzz.hb_glyph_info_t[] ParseString(harfbuzz.hb_font_t hbfont, string txt)
    {
        //初始化hbbug
        var buf = harfbuzz.wrap.hb_buffer_create();// new HarfBuzzSharp.Buffer();
        harfbuzz.wrap.hb_buffer_set_direction(buf, harfbuzz.hb_direction_t.HB_DIRECTION_LTR);//  buf.Direction = HarfBuzzSharp.Direction.LeftToRight;

        harfbuzz.wrap.hb_buffer_set_content_type(buf, harfbuzz.hb_buffer_content_type_t.HB_BUFFER_CONTENT_TYPE_UNICODE);   // buf.ContentType = HarfBuzzSharp.ContentType.Unicode;
        harfbuzz.wrap.hb_buffer_add_utf16(buf, txt); //buf.AddUtf16(outstr);
        harfbuzz.wrap.hb_buffer_guess_segment_properties(buf);    //buf.GuessSegmentProperties();//检查每一个字符串片段应该用啥方法处理

        harfbuzz.wrap.hb_shape(hbfont, buf); //hbfont.Shape(buf);//sharp之后，buf就从对应文本，变成对应字形

        //得到buf中的glyph信息列表，按这个让freetype画即可
        var hbinfo = harfbuzz.wrap.hb_buffer_get_glyph_infos(buf);// buf.GetGlyphInfoSpan();
        return hbinfo;
    }
    
    public static void InitCode(PictureBox pic1)
    {
        var lib = System.IO.File.ReadAllBytes("kalpurush.ttf");

        var hbfont = harfbuzz.wrap.hb_font_create(lib);
        var list = ParseString(hbfont, "প্রো >= 12");

        var libr = new SharpFont.Library();
        var face = new SharpFont.Face(libr, lib, 0);

        face.SetPixelSizes(64, 0);

        var bmp = new System.Drawing.Bitmap(1024, 256);
        int x = 0;
        for (var i = 0; i < list.Length; i++)
        {
            face.LoadGlyph(list[i].codepoint, SharpFont.LoadFlags.Default, SharpFont.LoadTarget.Normal);
            var addy = face.Glyph.Metrics.VerticalBearingY.ToInt32();

            var addx = face.Glyph.Advance.X.ToInt32();
            if (face.Glyph.Metrics.Width != 0)
            {
                //draw
                face.Glyph.RenderGlyph(SharpFont.RenderMode.Normal);
                var pitch = face.Glyph.Bitmap.Pitch;
                var mode = face.Glyph.Bitmap.PixelMode;
                var w = face.Glyph.Bitmap.Width;
                var h = face.Glyph.Bitmap.Rows;
                var sp = face.Glyph.Bitmap.BufferData;

                if (mode != SharpFont.PixelMode.Gray)
                    throw new Exception("only support gray");
                for (var sx = 0; sx < w; sx++)
                {
                    for (var sy = 0; sy < h; sy++)
                    {
                        var gray = sp[sy * pitch + sx];
                        var color = System.Drawing.Color.FromArgb(gray, 255, 0, 255);
                        bmp.SetPixel(sx + x, sy +addy , color);
                    }
                }
            }
            x += addx;
        }
        pic1.Image = bmp;
    }
}
